var staticServer="";//静态地址 最后不要带"/"

$(function () {
    showUserInfo();//头部显示用户信息
});
/**
 * 头部显示用户信息
 */
function showUserInfo() {
    setLoginInfo(function (json) {
        if (json.code === 0 && json.data.userId > 0) {
            var userName = json.data.displayName;
            // 头像
            var useImg = json.data.avatar;
            if (useImg == null || $.trim(useImg) === '') {
                useImg = '/static/qdxwx/img/avatar-boy.gif';
            } else {
                useImg = staticServer + useImg;
            }
            // 头部显示
            $("#userName").text(userName).attr('title', userName);
            $("#userAvatar").attr("src", useImg);
            $("#is-login").removeClass("layui-hide");
            $("#no-login").addClass("layui-hide");
            /*vip开通情况显示*/
            setVipInfo(function (vip) {
                if (vip.code === 0) {
                    $(".u-tit-vip").show();
                } else {
                    $(".u-tit-vip-gq").show();
                }
            });
            queryUnReadNum();// 查询未读消息
        } else {
            $("#is-login").addClass("layui-hide");
            $("#no-login").removeClass("layui-hide");
        }
    });
}
//验证用户登录
function isLogin(callback) {
    setLoginInfo(function (result) {
        if (result.code === 0) {
            callback(result.data);
        } else {
            layer.msg("此操作需要登录后方可继续，登录页面跳转中...", {time: 1500}, function () {
                location.href = "/auth/login.html";
            });
        }
    });
}
//获取登录用户
function setLoginInfo(callback) {
    $.ajax({
        url: '/ajax/user/current/info.json',
        type: 'get',
        dataType: 'json',
        success: function (result) {
            callback(result);
        }
    });
}
//获取vip开通信息
function setVipInfo(callback) {
    $.ajax({
        url: '/ajax/user/current/vip.json',
        type: 'post',
        dataType: 'json',
        success: function (result) {
            callback(result);
        }
    });
}
//用户退出登录
function exit() {
    $.ajax({
        url: '/ajax/user/logout.json',
        type: 'post',
        dataType: 'json',
        success: function (result) {
            window.location.reload();
        }
    });
}
//滚动定位
function cTabFun(op) {
    op.each(function () {
        var _this = $(this),
            _tName = _this.attr("name");
        _this.click(function () {
            _this.parent().parent().find("a").removeClass("current");
            _this.addClass("current").siblings().removeClass("current");
            //$("html,body").animate({"scrollTop":$("."+_tName+"-content").offset().top}, 500);
        })
    })
}
//tree menu
function treeMenu() {
    //一级目录
    $("#lh-menu>ul>li>a").each(function () {
        /*打开课程章节列表显示所有章节*/
        var _this = $(this);
        _this.siblings("ol").slideDown(150);
        _this.addClass("current-1");
        _this.click(function () {
            if (_this.siblings("ol").is(":hidden")) {
                _this.siblings("ol").slideDown(150);
                _this.addClass("current-1");
                //_this.parent("li").siblings().children("ol").slideUp(150);
                //_this.parent("li").siblings().children("a:first").removeClass("current-1");
            } else {
                _this.siblings("ol").slideUp(150);
                _this.removeClass("current-1");
            }
        });
    })
}

// scrollLoad 滚动响应加载调用图片方法
var scrollLoad = (function (options) {
    var defaults = (arguments.length === 0) ? {src: 'xSrc', time: 500} : {
        src: options.src || 'xSrc',
        time: options.time || 500
    };
    var camelize = function (s) {
        return s.replace(/-(\w)/g, function (strMatch, p1) {
            return p1.toUpperCase();
        });
    };
    this.getStyle = function (element, property) {
        if (arguments.length !== 2) return false;
        var value = element.style[camelize(property)];
        if (!value) {
            if (document.defaultView && document.defaultView.getComputedStyle) {
                var css = document.defaultView.getComputedStyle(element, null);
                value = css ? css.getPropertyValue(property) : null;
            } else if (element.currentStyle) {
                value = element.currentStyle[camelize(property)];
            }
        }
        return value === 'auto' ? '' : value;
    };
    var _init = function () {
        if (document.getElementById("aCoursesList") == null) {
            return;
        }
        var offsetPage = window.pageYOffset ? window.pageYOffset : window.document.documentElement.scrollTop,	//滚动条滚动高度
            offsetWindow = offsetPage + Number(window.innerHeight ? window.innerHeight : document.documentElement.clientHeight),
            docImg = document.getElementById("aCoursesList").getElementsByTagName("img"),			//通过ID查找获取图片节点
            _len = docImg.length;
        if (!_len) return false;
        for (var i = 0; i < _len; i++) {
            var attrSrc = docImg[i].getAttribute(defaults.src),
                o = docImg[i], tag = o.nodeName.toLowerCase();
            if (o) {
                postPage = o.getBoundingClientRect().top + window.document.documentElement.scrollTop + window.document.body.scrollTop;
                postWindow = postPage + Number(this.getStyle(o, 'height').replace('px', ''));
                if ((postPage > offsetPage && postPage < offsetWindow) || (postWindow > offsetPage && postWindow < offsetWindow)) {	//判断元素始终在可见区域内
                    if (tag === "img" && attrSrc !== null) {
                        o.setAttribute("src", attrSrc);
                    }
                    o = null;
                }
            }
        }
        window.onscroll = function () {
            setTimeout(function () {
                _init();
            }, defaults.time);
        }
    };
    return _init();
});
/**
 * 查询未读消息
 */
function queryUnReadNum() {
    $.ajax({
        type: "get",
        dataType: "json",
        url: "/ajax/user/current/letter.json",
        cache: true,
        async: true,
        success: function (result) {
            if (result.code === 0) {
                var letter = result.data;
                if (letter == null || letter.length === 0) {
                    /* 如果没有未读消息移除用于显示消息的div*/
                    $("#letter").parent().remove();
                    return;
                }
                var html = '';
                for (var i = 0; i < letter.length; i++) {
                    /*把未读消息放到数组*/
                    var letterInfo = letter[i];
                    var type = "";
                    if (letterInfo.type === 1) {
                        type = "系统消息"
                    } else if (letterInfo.type === 5) {
                        type = "课程过期"
                    } else if (letterInfo.type === 6) {
                        type = "优惠券过期"
                    }
                    /*把未读消息的内容和类型拼接到标签中*/
                    html += ' <li> <div class="t-n-nr"><em title="删除" onclick="removeMsg(' + letterInfo.id + ',this)" class="ico-n-cl icon16">&nbsp;</em><a title="查看详情" class="nr-tit" href="/user/letter.html">' + letterInfo.content + '</a></div></li>'
                }
                /* 把拼好的字符串标签放到页面 id=‘letter’位置*/
                $("#letter").append(html);
                //如果未读信息大于等于6条显示：显示更多
                if (letter.length >= 6) {
                    $("#letter").next().show();
                }
                if (letter.length > 0) {
                    $("#letterPoint").html(letter.length).show();
                }
            }
        }
    });
}

/*把系统消息改为已读*/
function removeMsg(letterId,obj) {
    $.ajax({
        url: "/user/ajax/changeStatus",
        data: {
            "id": letterId
        },
        type: "post",
        dataType: "json",
        success: function (result) {
            if (result.code === 0) {
                $(obj).parent().parent().remove();
                if ($("#letter").find("li").length <= 6) {
                    $(".new-tit-box").hide();
                }
                //消息数
                var letterLength = parseInt($("#letterPoint").html()) - 1;
                if (letterLength === 0) {
                    $("#letterPoint").html("");
                } else {
                    $("#letterPoint").html(letterLength);
                }
            }
        }
    });
}

//右侧浮动 在线客服，官方微信， 返回顶部
function goTopFun() {
    var _gt = $("#goTopBtn");
    _gt.bind("click", function () {
        $("html,body").animate({"scrollTop": 0}, 500);
    });
    var goTop = function () {
        var sTop = $(document).scrollTop();
        (sTop > 120) ? _gt.fadeIn(50) : _gt.fadeOut(50);
    };
    $(window).bind("scroll", goTop);
}

/**
 * 直播播放
 */
function livePlay(nodeId) {
    $.ajax({
        type: "POST", dataType: "json",
        url: "/user/live/play/check.json",
        data: {"nodeId": nodeId},
        success: function (result) {
            if (result.code === 0) {
                var heigth = $(window).height();
                window.location.href = "/user/live/play.html?nodeId=" + nodeId + "&width=100%&height=" + heigth;
            } else if (result.code === 401) {
                location.href = "/auth/login.html";
            } else {
                return layer.alert(result.msg);
            }
        }
    });
}
/**
 * 收藏课程
 */
function favorites(infoId,typeId, obj) {
    $.ajax({
        url: '/ajax/favorite/add.json',
        type: 'post',
        data: {"infoId": infoId, "typeId":typeId},
        dataType: 'json',
        success: function (result) {
            if (result.code === 0) {
                if (obj) {
                    $(obj).removeAttr("onclick").attr("onclick","deleteFavorite("+infoId+","+typeId+",this)").text("取消收藏");
                }
                layer.msg("收藏成功！", {icon: 1});
            } else if (result.code === 401) {
                location.href="/auth/login.html";
            } else {
                layer.msg(result.msg, {icon: 2});
            }
        }
    });
}
/**
 * 取消收藏
 */
function deleteFavorite(infoId, typeId, obj) {
    $.ajax({
        url: '/ajax/favorite/delete.json',
        type: 'post',
        data: {"infoId": infoId, "typeId":typeId},
        dataType: 'json',
        success: function (result) {
            if (result.code === 0) {
                if (obj) {
                    $(obj).removeAttr("onclick").attr("onclick","favorites("+infoId+","+typeId+",this)").text("收藏");
                }
                layer.msg("取消收藏成功！", {icon: 1});
            } else if (result.code === 401) {
                location.href="/auth/login.html";
            } else {
                layer.msg(result.msg, {icon: 2});
            }
        }
    })
}
function buyCourse(courseId) {
    if (courseId < 1) {
        return layer.msg("参数异常", {icon: 2});
    }
    isLogin(function () {
        layer.open({
            title: '课程报名',
            type: 2,
            area: ['815px', '576px'],
            content: '/order/course.html?courseId=' + courseId
        });
    });
}
function buyMember(typeId) {
    if (typeId === 0) {
        return layer.msg("请选择要购买的会员！", {icon: 2});
    }
    isLogin(function () {
        layer.open({
            type: 2,
            title: null,
            area: ['860px', '540px'],
            content: '/order/member.html?typeId=' + typeId
        });
    });
}
function buyPicture(pictureId) {
    if (pictureId < 1) {
        return layer.msg("参数异常", {icon: 2});
    }
    isLogin(function () {
        layer.open({
            title: '确认订单',
            type: 2,
            area: ['815px', '540px'],
            content: '/order/picture.html?pictureId=' + pictureId
        });
    });
}
function buyDocument(documentId) {
    if (documentId < 1) {
        return layer.msg("参数异常", {icon: 2});
    }
    isLogin(function () {
        layer.open({
            title: '资料购买',
            type: 2,
            area: ['815px', '576px'],
            content: '/order/document.html?documentId=' + documentId
        });
    });
}
//自定义方法-数组去重复
Array.prototype.unique = function() {
    var newArr = []; //一个新的临时数组
    for (var i = 0; i < this.length; i++) { //遍历当前数组
        if (this[i] === "") {
            continue;
        }
        //如果当前数组的第i已经保存进了临时数组，那么跳过，否则把当前项push到临时数组里面
        if (newArr.indexOf(this[i]) === -1) {
            newArr.push(this[i]);
        }
    }
    return newArr;
};

function isEmpty(str) {
    return str == null || str.trim() === '';
}

function isNotEmpty(str){
    return !isEmpty(str);
}

function isNotNull(object){
    return !isNull(object);
}

function isNull(object){
    return typeof (object) == "undefined" || object == null || object === '';
}

//获取URL中的参数
function getParameter(val) {
    var uri = window.location.search;
    var re = new RegExp("" + val + "=([^&?]*)", "ig");
    return ((uri.match(re)) ? (uri.match(re)[0].substr(val.length + 1)) : null);
}

//检查是否手机浏览
function isMobileBrowser() {
    var browser = navigator.userAgent.toLowerCase();
    var phone = /iphone|ipod|ipad|android|mobile|blackberry|webos|incognito|webmate|bada|nokia|lg|ucweb|skyfire|micromessenger/i;
    return phone.test(browser);
}
//减法
function subtraction(arg1, arg2) {
    var r1, r2, m, n;
    try {
        r1 = arg1.toString().split(".")[1].length;
    } catch (e) {
        r1 = 0;
    }
    try {
        r2 = arg2.toString().split(".")[1].length;
    } catch (e) {
        r2 = 0;
    }
    m = Math.pow(10, Math.max(r1, r2));
    //last modify by deeka
    //动态控制精度长度
    n = (r1 >= r2) ? r1 : r2;
    return ((arg1 * m - arg2 * m) / m).toFixed(n);
}

//兼容ie7/8 trim方法报错
Function.prototype.method = function(name, func) {
    this.prototype[name] = func;
    return this;
};
String.method('trim', function () {
    return this.replace(/^\s+|\s+$/g, '');
});
String.method('ltrim', function () {
    return this.replace(/^\s+/g, '');
});
String.method('rtrim', function () {
    return this.replace(/\s+$/g, '');
});
//正整数验证
function isNumber(str) {
    var number = /^[0-9]+$/;
    return number.test(str);
}

function isMobile(strVal) {
    if (strVal == null || strVal === "") {
        return false;
    }
    var reg = /^1{1}[0-9]{10}$/; //验证手机正则
    return reg.test(strVal);
}
//树形菜单(章节目录)
$(function() {
    $('.menu-item dt').on('click',function () {
        var _this = $(this);
        if(_this.hasClass('active')){
            _this.removeClass('active');
            _this.siblings('dd').slideDown(200);
        }else {
            _this.addClass('active');
            _this.siblings('dd').slideUp(200);
        }
    })
});